package com.xscha.soyue.common.core.exception.status;

import com.xscha.soyue.common.core.exception.SoyRuntimeException;

import java.util.Arrays;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * Title: SoyStatusCode Description: 错误枚举
 *
 * @author Vondser
 * @version V3.0.0
 * @date 2024/04/12
 */
public interface SoyStatusCode {

	Integer getCode();

	String getMessage();

	/**
	 * 必须是枚举并且实现了SoyStatusCode才能调用
	 */
	@SuppressWarnings("unchecked")
	default <E extends Enum<E> & SoyStatusCode> E instanceOf(Integer code) {
		Class<? extends SoyStatusCode> clz = this.getClass();
		if (Enum.class.isAssignableFrom(clz) && SoyStatusCode.class.isAssignableFrom(clz)) {
			return (E) of(code, (Class<E>) this.getClass());
		}
		throw new SoyRuntimeException(CommonStatusCode.DATA_CONVERT_ERROR, "类型转换错误，必须继承Enum<E> & SoyStatusCode");
	}

	static <E extends Enum<E> & SoyStatusCode> E of(Integer code, Class<E> cls) {
		return of(code, cls, () -> null);
	}

	static <E extends Enum<E> & SoyStatusCode> E of(Integer code, Class<E> cls, Supplier<E> defaultValue) {
		if (Objects.isNull(cls)) {
			return defaultValue.get();
		}
		return Arrays.stream(cls.getEnumConstants())
			.filter(e -> e.getCode().equals(code))
			.findFirst()
			.orElse(defaultValue.get());
	}

}
